package com.service;

import cn.hutool.core.util.RandomUtil;
import com.dao.StudentDAO;
import com.dao.UserDAO;
import com.pojo.Student;
import com.pojo.User;
import com.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@SuppressWarnings("ALL")
@Service
@Transactional
public class RegisterService {

    @Autowired
    private UserDAO userDAO;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private JavaMailSender javaMailSender;

    @Value("${spring.mail.username}")
    private String from;

    /**
     *
     * @param username 接收界面上的账号
     * @param mail      接收界面上的邮箱
     * @param password  接收界面上的密码
     * @return
     */
    public int addUser(String username,String mail,String password){
        User user = new User();
        Student student = new Student();
        user.setUserName(username);
        user.setUserPassword(MD5Util.string2MD5(password));
        user.setUser_mail(mail);

        int n = userDAO.addUser(user);
        if (n == 1){
            student.setStudent_username(username);
            userDAO.addstudent(student);
        }
        return n;
    }

    /**
     * 发送验证码到指定邮件
     * @param to
     */
    public void sendMail(String to)
    {
        //产生验证码
        String code = RandomUtil.randomString(4);

        //保存到redis
        redisTemplate.boundZSetOps("mail").add(to+":"+code,System.currentTimeMillis());

        SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
        simpleMailMessage.setFrom(from);
        simpleMailMessage.setTo(to);
        simpleMailMessage.setSubject("验证码");
        simpleMailMessage.setText("您的验证码是:"+code);
        javaMailSender.send(simpleMailMessage);
    }

    /**
     * 验证验证码是否正确
     * @param to  接收
     * @param code 验证码
     * @return
     */
    public boolean checkCode(String to, String code)
    {
        Long minchi = redisTemplate.opsForZSet().rank("mail",to+":"+code);
        if (minchi==null)
        {
            return false;
        }
        //存在还要删除
        redisTemplate.boundZSetOps("mail").removeRange(minchi,minchi);
        return true;
    }


}
